<template>
  <div ref="warp" class="contentWarpBox">
    <div class="searchInfo">
      <div class="left">
        <el-select
          v-model="searInfo.roleId"
          style="marginRight:5px;width:120px;"
          clearable
          placeholder="角色类型"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
        <el-input
          v-model="searInfo.keyword"
          placeholder="用户名"
          style="width:120px;marginRight:5px;"
          clearable
          width
        />
        <el-button type="primary" @click="searchInfoMationS">搜 索</el-button>
      </div>
      <el-button
        v-if="accreditChildren.createRoleUser"
        class="right"
        type="primary"
        @click="addRoleUser"
      >添加用户</el-button>
    </div>
    <el-table ref="table" :data="tableData" border stripe :height="this.$getTableHeight">
      <el-table-column label="用户编码">
        <template slot-scope="scope">{{ scope.row.userCode ?scope.row.userCode:"&nbsp;" }}</template>
      </el-table-column>
      <el-table-column prop="userName" label="用户名" />
      <el-table-column prop="roleName" label="所属角色" />
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.id">
            <span
              v-if="accreditChildren.deleteRoleUser"
              class="_delete"
              @click="deleteDic(scope.row)"
            >删除</span>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination clearfix">
      <Pagination
        class="right"
        :total-count="totalCount"
        :page-size="page.pageSize"
        :current-page="page.pageNo"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="添加用户"
      center
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="所属角色：" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择" @change="changeRoleId">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户：" prop="userName">
          <el-autocomplete
            v-model="form.userName"
            style="width:215px;"
            class="inline-input"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mmUrl from '~/utils/utilUrl';
import regular from '~/utils/regular';
import {
  _currentChange,
  _sizeChange,
  _changeTable,
  _deleteMethods,
  _searchInfo,
  reduceArr,
  createDics,
  changeTableHeight
} from '~/utils/util';
import Pagination from '~/components/commom/pagination';
export default {
  components: {
    Pagination
  },
  data() {
    return {
      form: {
        roleId: '',
        userId: '',
        userName: ''
      },
      accreditChildren: {},
      dialogVisible: false,
      totalCount: 0,
      rules: {
        roleId: regular.require1,
        userName: {
          trigger: 'change',
          validator: this.checkConnect
        }
      },
      searInfo: {
        keyword: '',
        roleId: ''
      },
      copysearInfo: {
        keyword: '',
        roleId: ''
      },
      page: {
        maxResultCount: 0,
        pageNo: 0,
        pageSize: 20,
        skipCount: 0
      },
      options: [],
      tableData: [],
      restaurants: []
    }
  },
  mounted() {
    this.initGetDate()
    const result = JSON.parse(sessionStorage.getItem('menu'))
    this.accreditArr = reduceArr(result, '/' + this.$route.name)
    this.accreditChildren = createDics(
      this.accreditArr.children,
      'permissionCode'
    )
    
  },
  methods: {
    checkConnect(rule, value, callback) {
      if (value === '') {
        callback(new Error('此项为必填项'))
      } else if (this.restaurants.some(v => v.value === value)) {
        callback()
      } else {
        callback(new Error('请输入正确的关联账户'))
      }
    },
    submitFrom() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$post({
            url: mmUrl.roleUser.create,
            data: {
              items: [
                {
                  roleId: this.form.roleId,
                  userId: this.form.userId
                }
              ]
            }
          }).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
            this.$refs['form'].resetFields()
            this.searchInfoMationS()
            this.dialogVisible = false
          })
        }
      })
    },
    changeRoleId() {
      this.form.userId = '';
      this.form.userName = '';
      this.restaurants = []
      this.$refs['form'].clearValidate()
      this.$post({
        url: mmUrl.roleUser.getUser,
        data: {
          roleId: this.form.roleId
        }
      }).then(res => {
        this.restaurants = res.map(v => ({
          value: `${v.userName}(${v.userCode})`,
          id: v.id
        }))
      })
    },
    addRoleUser() {
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    deleteDic(row) {
      const that = this
      _deleteMethods(mmUrl.roleUser.delete, row, that).then(() => {
        that.searchInfoMationS('no')
      })
    },
    searchInfoMationS(res) {
      this.copysearInfo = JSON.parse(JSON.stringify(this.searInfo))
      const result = _searchInfo(res, this.page, this.copysearInfo)
      this.changeTableData(result)
    },
    changeTableData(res) {
      const that = this
      _changeTable(mmUrl.roleUser.get, res, that)
    },
    handleSizeChange(val) {
      const result = _sizeChange(val, this.page, this.copysearInfo)
      this.changeTableData(result)
    },
    handleCurrentChange(val) {
      const result = _currentChange(val, this.page, this.copysearInfo)
      this.changeTableData(result)
    },
    handleSelect(item) {
      this.form.userId = item.id
      this.form.userName = item.value
    },
    querySearch(queryString, cb) {
      const restaurants = this.restaurants
      const results = queryString
        ? restaurants.filter(v => v.value.includes(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    initGetDate() {
      this.$post({
        url: mmUrl.roleUser.pageLoad,
        data: Object.assign({}, { page: this.page }, this.searInfo)
      }).then(res => {
        this.tableData = res.items.items
        this.options = res.roles
        this.totalCount = res.items.totalCount
        changeTableHeight(this)
      })
    }
  }
}
</script>

<style>
</style>
